<template>
  <div class="app-container">
    <el-dialog title="编辑图片" :visible.sync="isShowEditPicture" width="90%" append-to-body center
               @close="closeEditPicture">
      <div class="mb10" style="display: flex;align-items: center">
        <el-select ref="selectHeadEmpId" :disabled="isDisSelect" v-model="selectValue" multiple filterable
                   placeholder="选择图片标签" @change="chooseTag" style="width: 80%">
          <el-option v-for="item in tagList" :key="item.id" :label="item.tagName" :value="item.id"></el-option>
        </el-select>
        <div style="display: flex;align-items: center;margin: 10px 0">
          <el-button class="ml10" type="primary" size="small" @click="openAllocationModal">分配</el-button>
          <el-button class="ml10" type="primary" size="small" @click="handleSubmit('0')">暂存</el-button>
          <el-button class="ml20" type="success" size="small" @click="handleSubmit('1')">确认已优化</el-button>
          <el-button class="ml20" type="danger" size="small" @click="changeNotOptimized()">改为未优化</el-button>
        </div>
      </div>
      <el-tabs v-model="tabsValue" type="border-card" @tab-click="tabsClick">
        <el-tab-pane v-for="(item,index) in tabsList" :key="index" :label="item.label" :name="item.name">
          <el-table v-loading="loading" :data="imgDetailList" border stripe @selection-change="handleSelectionChange"
                    :key="isUpdateTable">
            <el-table-column type="selection" width="40" align="center"></el-table-column>
            <el-table-column label="原图" min-width="200" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.type == 2 || scope.row.type == 3">
                  <image-upload isLimitsize v-model="scope.row.optimizePic" :changeSize="true"
                                :isShowTip="false" :limit="1"/>
                </div>
                <div v-else>
                  <image-preview
                    :src="scope.row.optimizePic.indexOf('?') != -1?scope.row.optimizePic.substring(0, scope.row.optimizePic.indexOf('?')):scope.row.optimizePic"
                    width="70px" height="70px"></image-preview>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="元素图" min-width="500" align="center">
              <template slot-scope="scope">
                <div>
                  <image-upload isLimitsize :atlasType="tabsValue" :isShowSize="true" v-model="scope.row.pics"
                                :changeSize="true" :isShowTip="false" :limit="5" :tabValue="tabsValue"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="标签" min-width="350" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.tagList && scope.row.tagList.length>0">
                  <el-tag v-for="(tag,index) in scope.row.tagList" :key="index" style="margin-right: 5px">
                    {{ tag.tagName }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="指派人" min-width="150" align="center" prop="headUserName">
              <template slot-scope="scope">
                <div v-if="scope.row.headUserName">{{ scope.row.headUserName }}</div>
                <div v-else>未分配</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleEdit(scope.row, scope.$index)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!--    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"-->
      <!--                @pagination="getImageList"/>-->
    </el-dialog>
    <!--  分配任务弹窗  -->
    <el-dialog
      title="分配任务"
      :visible.sync="isShowAllocationModal"
      width="500px">
      <el-form :model="taskInfo" :rules="taskRules" ref="taskInfo" size="small"
               label-width="120px">
        <el-form-item label="指派人员：" prop="headUserId">
          <el-select v-model="taskInfo.headUserId" placeholder="请选择指派人员" filterable>
            <el-option v-for="(item,index) in peopleList" :key="index" :label="item.nickName"
                       :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务备注：" prop="remarks">
          <el-input @input="inputRemark" type="textarea" v-model="taskInfo.remarks" placeholder="请输入任务备注"
                    clearable/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowAllocationModal = false">取 消</el-button>
        <el-button type="primary" @click="alloctionTask">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑图片 -->
    <el-dialog
      title="编辑图片"
      :visible.sync="isEditPicture"
      width="1500px">
      <PictureEditor ref="pictureRef" :key="new Date().getTime()" :data="pictureData" :onCompleted="onCompleted"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  changePictureDetail,
  getCollectProductImage,
  getTagList,
  createPlanToHeadOptimize,
  queryOptimizeHeadUser,
  pictureEditor
} from '@/api/picture/picture'
import {makeProductNotOptimize} from "@/api/picture/optimizeTask"
import store from '@/store'
import PictureEditor from '@/components/PictureEditor'
import {bucketUpload} from "@/utils/alioss";
import {dataURLtoFile} from "@/utils/dataURLtoFile";
import uuid from '@/utils/uuid';

export default {
  props: {
    collectProductId: {
      type: String,
      default: ""
    }
  },
  components: {
    PictureEditor
  },
  data() {
    return {
      tagList: [],//标签列表
      isDisSelect: true,//是否禁用下拉框
      selectValue: "",//选择的标签
      isUpdateTable: false,
      loading: false, // 遮罩层
      chooseTableId: [], // 选中的table数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      total: 0, // 总条数
      imgDetailList: [], // 卖家订单表格数据
      chooseTagList: [],// 所选择标签的列表
      queryParams: {
        pageNum: 1,
        pageSize: 6,
      }, // 查询参数
      tabsValue: 0, //选项卡下标
      isShowEditPicture: true,
      tabsList: [
        {
          name: '0',
          label: '轮播图'
        }, {
          name: '1',
          label: '详情图'
        }, {
          name: '2',
          label: '营销图'
        }, {
          name: '3',
          label: '白底图'
        }
      ],//选项卡列表
      isShowAllocationModal: false,//是否打开分配任务弹窗
      taskInfo: {},// 任务信息
      taskRules: {
        headUserId: [{
          required: true,
          message: '请选择指派人员',
          trigger: 'change'
        }],
        remarks: [{
          required: true,
          message: '请输入备注',
          trigger: 'blur'
        }],
      },
      peopleList: [],//美工人员列表
      collectProductIds: [],//选中的采集商品列表
      chooseIds: [],//选中的图片列表
      optimizePics: [],//选中的采集商品原图图片列表
      isEditPicture: false,
      pictureData: {},
      editIndex: 0
    }
  },
  created() {
    this.getTagList()
    this.getPeopleList()
    window.addEventListener('message', this.receiveMessage, true);
  },
  methods: {
    onCompleted(data) {
      const op = dataURLtoFile(data[0], uuid() + '.jpg');
      this.handleUpload(op);
    },
    // 上传
    handleUpload(op) {
      let bucketName = '' // 桶名
      let dir = `images`
      bucketUpload(
        op,
        res => {
          let temp = {
            name: res.attachment,
            url: res.aliyunAddress,
            code: res.code
          }
          this.imgDetailList[this.editIndex].pics = temp.name;
          this.isEditPicture = false;
        },
        err => {
        },
        bucketName,
        dir
      )
    },
    receiveMessage(event) {
      if (event.data && !event.data.type) {
        const postData = JSON.parse(event.data);
        const {type, data} = postData;
        console.log('postData', postData)
        switch (type) {
          case 'base64':
            this.onCompleted(data);
            return false;
          case 'psd':
            this.onChange(data);
            return false;
          case 'autoHeight':
            const iframe = document.getElementById('editor-Iframe');
            iframe.style.height = data.editorHeight + 'px';
            return false;
          default:
            return false;
        }
      }
    },
    // 编辑图片
    handleEdit(row, index) {
      this.loading = true;
      const pics = (row.pics || '').split(';').filter(item => !!item);
      this.editIndex = index;
      if (pics.length > 0) var url = pics[0]
      else var url = row.optimizePic
      if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) url = store.getters.domain + url
      pictureEditor({url: url}).then(res => {
        if (res.code === 200) {
          this.loading = false;
          this.isEditPicture = true;
          this.pictureData = res.data;
          this.$nextTick(() => {
            this.$refs.pictureRef.init('1');
          })
        }
      })
    },
    // 获取美工人员列表
    getPeopleList() {
      queryOptimizeHeadUser().then(res => {
        this.peopleList = res.data.sysUserList
        // let list = res.data.sysUserList
        // list.map(item => {
        //   this.peopleList.push({
        //     label: item.nickName,
        //     value: item.userId
        //   })
        // })
      })
    },
    // 分配任务
    alloctionTask() {
      // this.taskInfo.collectProductId = this.collectProductIds.toString()
      // this.taskInfo.optimizePic = this.optimizePics.toString()
      this.taskInfo.ids = this.chooseIds.toString()
      this.taskInfo.type = this.tabsValue
      this.taskInfo.headUserName = this.peopleList.map(item => item.userId == this.taskInfo.headUserId ? item.nickName : "").toString().replace(/,/g, "")
      createPlanToHeadOptimize(this.taskInfo).then(res => {
        this.$message({
          type: 'success',
          message: res.msg
        })
        this.isShowAllocationModal = false
        this.getImageList() // 更新优化列表
      })
    },
    // 关闭编辑图片弹窗
    closeEditPicture() {
      this.isShowEditPicture = false
      this.$emit('imgDetailSwitch', this.isShowEditPicture)
    },
    // 打开分配任务弹窗
    openAllocationModal() {
      // if (this.chooseTableId && this.chooseTableId.length != 1) {
      //   this.$message.error('请选择一张图片！')
      //   return
      // }
      this.taskInfo = {}

      // if (this.chooseTableId && this.chooseTableId.length > 1) {
      //   this.$message.error('请最多选择一项！')
      //   return
      // }
      if (this.chooseIds && this.chooseIds.length < 1) {
        this.$message.error("请至少选择一项！")
        return
      }
      if (this.tabsValue == 0 || this.tabsValue == 3) {
        this.taskInfo.remarks = "尺寸：800*800，要求："
      } else {
        this.taskInfo.remarks = "尺寸：750*1000，要求："
      }

      this.isShowAllocationModal = true
    },
    inputRemark(e) {
      this.$forceUpdate()
      // if (this.tabsValue == 0 || this.tabsValue == 3) {
      //   this.taskInfo.remarks = "尺寸：800*800  要求：" + e
      // } else {
      //   this.taskInfo.remarks = "尺寸：700*1000  要求：" + e
      // }
    },
    // 改为未优化
    changeNotOptimized() {
      this.$confirm("是否确定改为未优化", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        let data = {
          collectProductId: this.collectProductId,
        }
        makeProductNotOptimize(data).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
          // this.isShowEditPicture = false
          // this.$emit('imgDetailSwitch', this.isShowEditPicture)
          this.getImageList() // 修改完状态后再次获取订单列表
        })
      }).catch(() => {

      })
    },
    //  提交编辑图片
    handleSubmit(isSave) {
      if (this.chooseTableId && this.chooseTableId.length < 1) {
        this.$message.error('请至少选择一项！')
        return
      }
      // for (let i = 0; i < this.imgDetailList.length; i++) {
      //   if (!this.imgDetailList[i].optimizePic) {
      //     this.$message.error('请上传原图，图片不能为空')
      //     return
      //   }
      //   // if (!this.imgDetailList[i].pics) {
      //   //   this.$message.error('请上传元素图片')
      //   //   return
      //   // }
      //   // if (!this.imgDetailList[i].tagIds) {
      //   //   this.$message.error('请先选择标签')
      //   //   return
      //   // }
      // }
      let mssage = isSave == 0 ? "是否确定暂存所编辑的图片？" : "是否确定提交所编辑的图片，变为已优化状态？";
      this.$confirm(mssage, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        let data = {
          type: this.tabsValue,
          list: this.imgDetailList,
          collectProductId: this.collectProductId,
          isSave: isSave
        }
        changePictureDetail(data).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
          // this.isShowEditPicture = false
          // this.$emit('imgDetailSwitch', this.isShowEditPicture)
          this.getImageList() // 修改完状态后再次获取订单列表
        })
      }).catch(() => {

      })
    },
    // 选择标签
    chooseTag(e) {
      let tagList = this.tagList.filter(item => e.indexOf(item.id) > -1)
      let list = [];
      tagList.map(item => {
        if (e.indexOf(item.id) > -1) {
          list.push(item.id)
        }
      })
      for (let i = 0; i < this.imgDetailList.length; i++) {
        for (let j = 0; j < this.chooseTableId.length; j++) {
          if (i == this.chooseTableId[j]) {
            this.imgDetailList[i].tagIds = list.toString()
            this.imgDetailList[i].tagList = tagList
          }
        }
      }
      this.isUpdateTable = !this.isUpdateTable
    },
    // 获取标签列表
    getTagList() {
      getTagList(this.queryParams).then(response => {
        this.tagList = response.data
        this.getImageList()
      })
    },
    // // 切换选项卡前触发
    // beforeLeave(activeName, oldActiveName) {
    //   this.$confirm('切换后未提交的内容将会清空，是否确定切换?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     return false
    //   })
    // },
    // 切换选项卡
    tabsClick(tab, event) {
      this.selectValue = "" //把下拉框的值置为空
      this.isDisSelect = true
      console.log(tab, event)
      // this.isUpdateTable = !this.isUpdateTable
      this.getImageList(tab.index)
    },
    // 获取图片列表
    getImageList(index) {
      this.loading = true
      let data = {
        collectProductId: this.collectProductId,
        type: this.tabsValue
      }
      getCollectProductImage(data).then(response => {
        let list = response.data.picList
        console.log(list)
        for (let i = 0; i < list.length; i++) {
          list[i]['imgId'] = i
          if (list[i].tagIds) {
            let tagIds = list[i].tagIds.split(',')
            list[i]['tagList'] = this.tagList.filter(item => tagIds.indexOf(item.id) > -1)
          }
        }
        this.imgDetailList = list
        this.total = this.imgDetailList.length
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.chooseTableId = selection.map(item => item.imgId)
      // this.collectProductIds = selection.map(item => item.collectProductId)
      this.chooseIds = selection.map(item => item.id)
      this.optimizePics = selection.map(item => item.optimizePic)
      if (this.chooseTableId && this.chooseTableId.length > 0) {
        this.isDisSelect = false
      } else {
        this.isDisSelect = true
        this.selectValue = ""
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
  }
}
</script>
<style>
.demo-table-expand label {
  width: 100px;
  color: #99a9bf;
  padding: 0;
}
</style>
